package org.six11.olive3.picturephone.server;

import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;

import org.six11.olive3.net.Message;
import org.six11.util2.Debug;

/**
 * 
 *
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class MessageQueue {

  private Queue<Message> messages;
  private String uid;
  
  public MessageQueue(String uid) {
    this.uid = uid;
    messages = new LinkedList<Message>();
  }
  
  public void add(Message m) {
    synchronized (messages) {
      messages.add(m);
      messages.notifyAll();
    }
  }
  
  public void flush(PrintWriter out, boolean hold) {
    synchronized (messages) {
      Message m;
      if (hold && messages.isEmpty()) {
        try {
          messages.wait(5000);
        } catch (InterruptedException ex) {
          ex.printStackTrace();
        }
      }
      while ((m = messages.poll()) != null) {
        out.write(m.toOliveString());
      }
    }
  }
  
  private void bug(String what) {
    Debug.out("MessageQueue", what);
  }
}
